package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.config.WXConfig;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.WeixinPayService;
import com.qingcheng.util.HttpClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:boy
 * @Date:2019/7/21
 * @description:
 * @ModifiedBy:
 */
@Service(interfaceClass = WeixinPayService.class)
public class WeixinPayServiceImpl implements WeixinPayService {
    @Autowired
    private WXConfig wxConfig;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public Map createNative(String orderId, Integer money, String notifyUrl) {
        try {
            Map<String, String> param = new HashMap<String, String>();
            param.put("appid", wxConfig.getAppID());//公众号
            param.put("mch_id", wxConfig.getMchID());//商户号
            param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字 符串
            param.put("body", "青橙");//商品描述
            param.put("out_trade_no", orderId);//商户订单号
            param.put("total_fee", money + "");//总金额（分）
            param.put("spbill_create_ip", "127.0.0.1");//IP
            param.put("notify_url", notifyUrl);//暂时随便写一个
            param.put("trade_type", "NATIVE");//交易类型
            String xmlParam = WXPayUtil.generateSignedXml(param, wxConfig.getKey());
            WXPayRequest request = new WXPayRequest(wxConfig);
            String xmlResult = request.requestWithCert("/pay/unifiedorder", null, xmlParam, false);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlResult);
            Map<String, String> map = new HashMap<String, String>();
            map.put("code_url", resultMap.get("code_url"));
            map.put("total_fee", money + "");
            map.put("out_trade_no", orderId);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    public void notifyLogic(String xml) {
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            boolean valid = WXPayUtil.isSignatureValid(map, wxConfig.getKey());
            System.out.println("签名是否正确："+valid);
            System.out.println(map.get("out_trade_no"));
            System.out.println(map.get("result_code"));
            if (valid&&"SUCCESS".equals(map.get("result_code"))){
                rabbitTemplate.convertAndSend("paynotify","",map.get("out_trade_no"));
                orderService.updatePayStatus(map.get("out_trade_no"),map.get("transaction_id") );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, String> queryPayStatus(String orderId) {
        return null;
    }

    @Override
    public Map<String, String> closePay(Long orderId) throws Exception {
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("appid",wxConfig.getAppID());
        paramMap.put("mch_id",wxConfig.getMchID());
        paramMap.put("monce_str",WXPayUtil.generateNonceStr());
        paramMap.put("out_trade_no",orderId+"");
        String signedXml = WXPayUtil.generateSignedXml(paramMap, wxConfig.getKey());
        String url="https://api.mch.weixin.qq.com/pay/closeorder";
        HttpClient httpClient=new HttpClient(url);
        httpClient.setXmlParam(signedXml);
        httpClient.setHttps(true);
        httpClient.post();
        String content = httpClient.getContent();
        return WXPayUtil.xmlToMap(content);
    }
}
